package com.llap.exp190929.entity;

import com.llap.exp190929.security.JwtUser;
import lombok.Data;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

import javax.persistence.*;
import java.util.Date;

@Entity
@Data
@DynamicInsert
@DynamicUpdate
@Table(indexes = {
        @Index(name = "index_user_username", columnList = "username", unique = true)
})
public class User {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
    @Column(nullable = false, length = 32) private String username;
    @Column(nullable = false, length = 32) private String password;
    @Column private Integer age;
    @Column private Integer sex;
    @Column private String nickname;
    @Column private String realName;
    @Column private String mobile;
    @Column private String address;
    @Column(nullable = false) private boolean admin = false;
    @Column private String avatar;
    @Column(nullable = false) private boolean suspended = false;

    @Column(columnDefinition = "timestamp default CURRENT_TIMESTAMP", updatable = false)
    @Generated(GenerationTime.INSERT) private Date registerTime;

    @Column(columnDefinition = "timestamp default CURRENT_TIMESTAMP")
    @Generated(GenerationTime.ALWAYS) private Date updateTime;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.REFRESH}, fetch = FetchType.EAGER)
    private UserType userType;

    public User eraseCredential() {
        this.setPassword(null);
        return this;
    }

    public static User from(JwtUser jwtUser) {
        User ret = null;
        if (jwtUser != null) {
            ret = new User();
            ret.setId(jwtUser.getId());
            ret.setUsername(jwtUser.getUsername());
        }
        return ret;
    }

    public boolean is(User user) {
        return this.getUsername().equals(user.getUsername()) && this.getId().equals(user.getId());
    }

}
